package org.example.server.read;

import org.example.models.OnlineUsers;
import org.example.models.Server;
import org.example.websocket.SocketInterceptor;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ConcurrentHashMap;

public class RegisterStrategy extends ReadStrategy {
    @Override
    public void operateData() {
        try {
            String userID = dataJsonObject.getString("userID");
            ConcurrentHashMap hashmap = OnlineUsers.getInstance();
            hashmap.put(userID, socket);
            String json =
                    "{\n" +
                    "   \"type\": \"server\",\n" +
                    "   \"data\": {\n" +
                    "       \"operation\": \"setUserNumber\",\n" +
                    "       \"serverID\": \"" + SocketInterceptor.id + "\",\n" +
                    "       \"userNumber\": \"" + hashmap.size() + "\"\n" +
                    "   }\n" +
                    "}";
            Socket socket = new Socket(Server.getMainServerIP(), Server.getMainServerPort());
            PrintWriter pw = new PrintWriter(socket.getOutputStream());
            synchronized (pw) {
                pw.write(json);
                pw.flush();

                byte[] bytes = new byte[8];
                InputStream is = socket.getInputStream();
                is.read(bytes);
                System.out.println("更改在线人数返回状态: " + (new String(bytes)).trim());
                is.close();
            }
            pw.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
